package io.noties.markwon.base.core.spans


import android.text.style.LeadingMarginSpan

import android.graphics.Canvas
import android.graphics.Paint

import android.text.Layout
import com.gitee.wsl.ext.base.setAlpha
import io.noties.markwon.theme.MarkwonTheme

class BlockQuoteSpan(private val theme: MarkwonTheme) : LeadingMarginSpan {
    private val rect = ObjectsPool.rect()
    private val paint = ObjectsPool.paint()
    override fun getLeadingMargin(first: Boolean): Int {
        return theme.typography.blockMargin
    }

    override fun drawLeadingMargin(
        c: Canvas,
        p: Paint,
        x: Int,
        dir: Int,
        top: Int,
        baseline: Int,
        bottom: Int,
        text: CharSequence,
        start: Int,
        end: Int,
        first: Boolean,
        layout: Layout
    ) {
        val width = theme.typography.blockQuoteWidth
        paint.set(p)
        applyBlockQuoteStyle(paint)
        val left: Int
        val right: Int
        run {
            val l = x + dir * width
            val r = l + dir * width
            left = l.coerceAtMost(r)
            right = l.coerceAtLeast(r)
        }
        rect[left, top, right] = bottom
        c.drawRect(rect, paint)
    }

    private fun applyBlockQuoteStyle(paint: Paint) {
        val color: Int
        val blockQuoteColor = theme.colorTheme.blockQuoteColor.toInt()
        color = if (blockQuoteColor == 0) {
            paint.color.setAlpha(BLOCK_QUOTE_DEF_COLOR_ALPHA)
        } else {
            blockQuoteColor
        }
        paint.style = Paint.Style.FILL
        paint.color = color
    }

    companion object {
        protected const val BLOCK_QUOTE_DEF_COLOR_ALPHA = 25
    }
}